const Router = require('../../utils/router')
const { TeacherService } = require('../../services/index')
const Logger = require('../../utils/logger')
const Track = require('../../utils/track')

/**
 * pages/teacher-main/index
 * 教师课程主页 - TabBar页面
 */
Page({
  data: {
    // 搜索相关
    searchKeyword: '',
    hotKeywords: ['英语', '数学', '编程', '音乐', '美术'],
    
    // 分类数据
    categories: [],
    selectedCategoryId: '',
    
    // 地区选择
    selectedRegion: {
      province: '',
      city: '',
      district: ''
    },
    showRegionPicker: false,
    
    // 推荐数据
    featuredCourses: [],
    popularTeachers: [],
    
    // 加载状态
    loading: false,
    refreshing: false,
    
    // 统计数据
    stats: {
      totalCourses: 0,
      totalTeachers: 0,
      onlineStudents: 0
    }
  },

  /**
   * 页面加载
   */
  onLoad(options) {
    Logger.info('Page loaded: /pages/teacher-main/index', options)
    Track.trackPageView('/pages/teacher-main/index', options)
    
    this.initData()
  },

  /**
   * 页面显示
   */
  onShow() {
    this.refreshData()
  },

  /**
   * 下拉刷新
   */
  onPullDownRefresh() {
    this.refreshData(true)
  },

  /**
   * 初始化数据
   */
  async initData() {
    this.setData({ loading: true })
    
    try {
      await Promise.all([
        this.loadCategories(),
        this.loadFeaturedCourses(),
        this.loadPopularTeachers(),
        this.loadStats()
      ])
    } catch (error) {
      Logger.error('Failed to load teacher main data', error)
      wx.showToast({
        title: '加载失败，请重试',
        icon: 'none'
      })
    } finally {
      this.setData({ loading: false })
    }
  },

  /**
   * 刷新数据
   */
  async refreshData(isPullRefresh = false) {
    if (isPullRefresh) {
      this.setData({ refreshing: true })
    }
    
    try {
      await this.initData()
    } finally {
      if (isPullRefresh) {
        this.setData({ refreshing: false })
        wx.stopPullDownRefresh()
      }
    }
  },

  /**
   * 加载课程分类
   */
  async loadCategories() {
    try {
      const response = await TeacherService.getRootCategories()
      this.setData({
        categories: response.data || []
      })
    } catch (error) {
      Logger.error('Failed to load categories', error)
    }
  },

  /**
   * 加载精选课程
   */
  async loadFeaturedCourses() {
    try {
      const response = await TeacherService.getCourseList({
        page: 1,
        page_size: 6,
        is_featured: true
      })
      this.setData({
        featuredCourses: response.data?.list || []
      })
    } catch (error) {
      Logger.error('Failed to load featured courses', error)
    }
  },

  /**
   * 加载热门教师
   */
  async loadPopularTeachers() {
    try {
      const response = await TeacherService.getTeacherList({
        page: 1,
        page_size: 4,
        sort: 'rating'
      })
      this.setData({
        popularTeachers: response.data?.list || []
      })
    } catch (error) {
      Logger.error('Failed to load popular teachers', error)
    }
  },

  /**
   * 加载统计数据
   */
  async loadStats() {
    try {
      // 模拟统计数据，实际应该从API获取
      this.setData({
        stats: {
          totalCourses: 1520,
          totalTeachers: 286,
          onlineStudents: 8432
        }
      })
    } catch (error) {
      Logger.error('Failed to load stats', error)
    }
  },

  /**
   * 搜索输入
   */
  onSearchInput(e) {
    this.setData({
      searchKeyword: e.detail.value
    })
  },

  /**
   * 搜索提交
   */
  onSearchSubmit() {
    const { searchKeyword } = this.data
    if (!searchKeyword.trim()) return
    
    Track.trackClick('teacher_main_search', 'search', { keyword: searchKeyword })
    
    // 跳转到课程列表页面，传递搜索关键词
    Router.navigateTo(`/packageTeacher/pages/courses/list/index?keyword=${encodeURIComponent(searchKeyword)}`)
  },

  /**
   * 热门关键词点击
   */
  onHotKeywordTap(e) {
    const { keyword } = e.currentTarget.dataset
    Track.trackClick('teacher_main_hot_keyword', 'click', { keyword })
    
    Router.navigateTo(`/packageTeacher/pages/courses/list/index?keyword=${encodeURIComponent(keyword)}`)
  },

  /**
   * 分类选择
   */
  onCategoryTap(e) {
    const { category } = e.currentTarget.dataset
    Track.trackClick('teacher_main_category', 'click', { categoryId: category.id })
    
    Router.navigateTo(`/packageTeacher/pages/courses/list/index?category_id=${category.id}&categoryName=${encodeURIComponent(category.name)}`)
  },

  /**
   * 地区选择器显示
   */
  onRegionPickerShow() {
    this.setData({ showRegionPicker: true })
  },

  /**
   * 地区选择器隐藏
   */
  onRegionPickerHide() {
    this.setData({ showRegionPicker: false })
  },

  /**
   * 地区选择确认
   */
  onRegionConfirm(e) {
    const { province, city, district } = e.detail
    Track.trackClick('teacher_main_region', 'select', { province, city, district })
    
    this.setData({
      selectedRegion: { province, city, district },
      showRegionPicker: false
    })
    
    // 跳转到课程列表，传递地区信息
    Router.navigateTo(`/packageTeacher/pages/courses/list/index?province=${encodeURIComponent(province)}&city=${encodeURIComponent(city)}&district=${encodeURIComponent(district)}`)
  },

  /**
   * 查看全部课程
   */
  onViewAllCourses() {
    Track.trackClick('teacher_main_view_all_courses', 'click')
    Router.navigateTo('/packageTeacher/pages/courses/list/index')
  },

  /**
   * 查看全部教师
   */
  onViewAllTeachers() {
    Track.trackClick('teacher_main_view_all_teachers', 'click')
    Router.navigateTo('/packageTeacher/pages/list/index')
  },

  /**
   * 课程项点击
   */
  onCourseItemTap(e) {
    const { course } = e.currentTarget.dataset
    Track.trackClick('teacher_main_course_item', 'click', { courseId: course.id })
    
    Router.navigateTo(`/packageTeacher/pages/courses/detail/index?id=${course.id}`)
  },

  /**
   * 教师项点击
   */
  onTeacherItemTap(e) {
    const { teacher } = e.currentTarget.dataset
    Track.trackClick('teacher_main_teacher_item', 'click', { teacherId: teacher.id })
    
    Router.navigateTo(`/packageTeacher/pages/detail/index?id=${teacher.id}`)
  },

  /**
   * 统计项点击
   */
  onStatItemTap(e) {
    const { type } = e.currentTarget.dataset
    Track.trackClick('teacher_main_stat_item', 'click', { type })
    
    switch (type) {
      case 'courses':
        Router.navigateTo('/packageTeacher/pages/courses/list/index')
        break
      case 'teachers':
        Router.navigateTo('/packageTeacher/pages/list/index')
        break
      case 'students':
        // 可以跳转到学员相关页面
        wx.showToast({
          title: '功能开发中',
          icon: 'none'
        })
        break
    }
  },

  /**
   * 分享给朋友
   */
  onShareAppMessage() {
    return {
      title: '智慧社区 - 优质课程等你来',
      desc: '汇聚优秀教师，提供精品课程',
      path: '/pages/teacher-main/index',
      imageUrl: '/images/share-default.jpg'
    }
  },

  /**
   * 分享到朋友圈
   */
  onShareTimeline() {
    return {
      title: '智慧社区 - 优质课程等你来',
      desc: '汇聚优秀教师，提供精品课程',
      path: '/pages/teacher-main/index',
      imageUrl: '/images/share-default.jpg'
    }
  }
})
